package zhongbo.javaweb.instagram.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zhongbo.javaweb.instagram.dto.JsonRespDto;
import zhongbo.javaweb.instagram.dto.WsMsgDto;
import zhongbo.javaweb.instagram.enums.WsMethod;
import zhongbo.javaweb.instagram.schedule.HeartBeatCheckSchedule;

import javax.websocket.Session;

/**
 * 说明：
 *
 * @author zhongboWork
 * @version 1.0
 * @since 2022-01-06 18:21
 */
@Service
@Slf4j
public class WebSocketService {

    @Autowired
    private HeartBeatCheckSchedule heartBeatCheckSchedule;

    public boolean updateMessage(String message, Session session) {
        try {
            WsMsgDto wsMsgDto = JSON.parseObject(message, WsMsgDto.class);
            WsMethod method = wsMsgDto.getMethod();
            if (method != null) {
                if (method == WsMethod.ping) {
                    respPong(session);
                }
                return true;
            }
        } catch (Exception e) {
            log.error("未识别的ws消息: {}", message);
        }
        return false;
    }

    private void respPong(Session session) {
        try {
            sendMessage(session, new JsonRespDto<>().makeSuccess());
            heartBeatCheckSchedule.heartBeat();
        } catch (Exception e) {
            log.error("响应pong失败!", e);
        }
    }

    private void sendMessage(Session session, JsonRespDto<Object> resp) throws Exception {
        String jsonString = JSON.toJSONString(resp);
        session.getBasicRemote().sendText(jsonString);
    }
}
